from django.shortcuts import render
from django.views import View
from apps.centents.utils import get_channel_dict
from apps.goods.models import GoodsCategory, SKU,GoodsVisitCount
from apps.goods.utils import get_bread_dict
from meiduo_mall.settings.dev import logger
from django.http import HttpResponseForbidden,JsonResponse
from django.core.paginator import Paginator
from utils.response_code import RETCODE
import django_redis
from datetime import datetime
import json



# 统计同一类商品的访问情况
class VisitView(View):
    """
    实现思路：通过创建另一个表，这个表中有访问日期，访问数据的类型
    和访问次数，访问数据的类型字段是外键，通过与sku关联实现用category_id访问这个表
    每次访问表的访问字段加1,已每一天作为记录，如果当天的记录没有就创建，有的话就在访问字段加1
    """
    def post(self,request,category_id):
        # .获取当前的时间
        now = datetime.now().strftime('%Y-%m-%d')
        try:
            visit = GoodsVisitCount.objects.get(date=now,category_id=category_id)
        except Exception :
            visit = GoodsVisitCount.objects.create(
            date=now,count=0,category_id=category_id)
        visit.count += 1
        visit.save()
        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK'})
# 商品详情页展示
class DetailView(View):
    def get(self,request,sku_id):
        try:
            sku_ob = SKU.objects.get(id=sku_id)
            category_id = sku_ob.category
        except Exception as f:
            logger.error(f)
            return HttpResponseForbidden("404")
        categories = get_channel_dict()
        breadcrumb = get_bread_dict(category_id)
        context={
            'categories':categories,
            'breadcrumb':breadcrumb,
            'sku':sku_ob,
        }
        return render(request,"detail.html",context)
# 热销商品展示
class HotView(View):
    """
    通过传入的categroy_id 获取到指定的sku，根据销量排名，取前2
    返回ajax数据类型
    """
    def get(self,requset,category_id):
        try:
            sku_obes = SKU.objects.filter(category_id=category_id,is_launched=True).order_by("-sales")[:2]
        except Exception as f :
            logger.error(f)
            return HttpResponseForbidden("categroy_id错误")
        hot_skus = [ ]
        for sku_ob in sku_obes :
            hot_skus.append({
                "id":sku_ob.id,
                "default_image":sku_ob.default_image.url,
                "name":sku_ob.name,
                "price":sku_ob.price
            })

        return JsonResponse({
            "code":RETCODE.OK,
            "errmsg":"OK",
            "hot_skus":hot_skus
        })
# 排序和分页
class ListView(View):
    def get(self, request, category_id, page_num):
        # 商品详情页
        advertise = get_channel_dict()
        # 面包屑组建
        try:
            categort = GoodsCategory.objects.get(id=category_id)
        except Exception as f:
            logger.error(f)
            return HttpResponseForbidden("categoryid不存在")
        bread = get_bread_dict(categort)
        """
        排序方法，前端会发送一个ajxj请求，会携带一个querty参数，获取参数后根据要求排序
        1.默认，无需变化
        2.price : 通过category外键找到sku的表，再找到sku的价格，根据价格显示
        3.hot：通过category外键找到sku的表，再找到sku的销量，根据销量显示
        """
        sort_ob = request.GET.get("sort")
        if sort_ob == "price":
            # 通过指定的商品对象获取到指定的sku对象集合
            sku_ob = "price"
        elif sort_ob == "hot":
            sku_ob = "-sales"
        else:
            sku_ob = "create_time"
        skus = categort.sku_set.filter(is_launched=True).order_by(sku_ob)
        # print(skus)
        """
        分页：调用django自带的分页器，Paginator
        """
        # 生成分页器对象，传入两个参数，分别是数据和每页显示的数据
        page_ob = Paginator(skus, 5)
        try:
            # 获取当前页的数据
            page_skus = page_ob.page(page_num)
        except Exception as f:
            logger.error(f)
            return HttpResponseForbidden("页码不存在")
        # 获取总页数
        total_page = page_ob.num_pages
        context = {
            'categories': advertise,  # 频道分类
            'breadcrumb': bread,  # 面包屑导航
            'sort': sort_ob,  # 排序字段
            'category': categort,  # 第三级分类
            'page_skus': page_skus,  # 分页后数据
            'total_page': total_page,  # 总页数
            'page_num': page_num,  # 当前页码
        }

        return render(request, 'list.html', context)
